import { delOfflineStudyPlan, getOffLineCodeUrl, updateOfflinePlanStatus } from '@/api/OfflineStudy';
import type { StudyPlanListItem, StudyPlanListSearchParams } from '@/api/Plan';
import {
  deleteCircleStudyPlan,
  deleteFixedStudyPlan,
  secPlanList,
  switchCircleStudyPlanStatus,
  switchFixedStudyPlanStatus,
  updateCircleStudyPlanEffectiveTime,
} from '@/api/Plan';
import { ENTSTUDYOBJECTOPTIONS, StudyObjectEnum } from '@/common';
import CusDrawer from '@/components/CusDrawer';
import CusModal from '@/components/CusModal';
import useCacheColumns from '@/hooks/useCacheColumns';
import { useAppSelector } from '@/redux/store';
import { App, Button, Space, Spin, Switch } from 'antd';
import dayjs from 'dayjs';
import React, { useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import ExportCodeModal from './components/ExportCodeModal';
import StudyOfflineDetail from './components/StudyOfflineDetail';
import StudyPlanDetail from './components/StudyPlanDetail';
import StudyPlanTemplateDrawer from './components/StudyPlanTemplateDrawer';
import StudyPlanTimeForm from './components/StudyPlanTimeForm';

type SearchValue = Partial<StudyPlanListSearchParams>;

type TableRecord = StudyPlanListItem & { showEditButton?: boolean };
interface DataType {
  key: React.Key;
  size: string;
  width: string;
  height: string;
  leng: string;
}
const DRAWERWIDTH = 750;
const sourceData: DataType[] = [
  {
    key: '1',
    size: 'a',
    width: '8',
    height: '8',
    leng: '0.5',
  },
  {
    key: '2',
    size: 'b',
    width: '12',
    height: '12',
    leng: '0.8',
  },
  {
    key: '3',
    size: 'c',
    width: '15',
    height: '15',
    leng: '1',
  },
  {
    key: '4',
    size: 'd',
    width: '30',
    height: '30',
    leng: '1.5',
  },
  {
    key: '5',
    size: 'e',
    width: '50',
    height: '50',
    leng: '2.5',
  },
];
export default function StudyPlanPage() {
  const {
    message,
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const { entId } = useAppSelector((state) => state.loginEnt);
  const [refreshFlag, _setRefreshFlag] = useState(false);
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string }>({ show: false });
  const [nowModal, setNowModal] = useState<number>(1); // 1 开启计划弹窗  2导出二维码弹窗
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const studyPlanTimeFormRef = useRef<{ onSubmit: () => Promise<any> }>(null);
  const exportCodeModalRef = useRef<{ onSubmit: () => Promise<any> }>(null);
  const [curPlanCourseId, setCurPlanCourseId] = useState<string>();
  const [currStudyMethod, setCurrStudyMethod] = useState<any>();
  const [currPlanType, setCurrPlanType] = useState<string>();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const studyPlanTemplateDrawerRef = useRef<{ open: () => void }>(null);
  const { loginRole } = useAppSelector((state) => state.loginUser);

  // 刷新table的 flag
  function refreshTable() {
    _setRefreshFlag((v) => !v);
  }

  function _noPermissionToSwitch(res: any) {
    const { code, data, msg } = res;
    // console.log('--res--:', res);
    if (code === '200') {
      if (data === 1) {
        confirm({
          title: '开启失败',
          content: msg,
          centered: true,
          okText: '前往',
          onOk: () => {
            if (loginRole == '1' || loginRole == '0') {
              navigator('/safeService/bitAllocation');
            } else {
              message.warning('您暂无权限，请联系企业管理人员！');
            }
          },
        });
      } else if (data.promptMessage) {
        confirm({
          title: '开启成功',
          content: data.promptMessage,
          centered: true,
          okText: '前往',
          onOk: () => {
            if (loginRole == '1' || loginRole == '0') {
              navigator('/safeService/buyService');
            } else {
              message.warning('您暂无权限，请联系企业管理人员！');
            }
          },
        });
      } else {
        message.success('状态修改成功');
        refreshTable();
      }
    }
  }

  //状态更改--循环计划接口
  const switchCircleStudyPlanOpenStatusApi = (guid: string, originOpenStatus: number) => {
    switchCircleStudyPlanStatus({ guid, openStatus: originOpenStatus ? 0 : 1, entId })
      .then((res: any) => {
        _noPermissionToSwitch(res);
      })
      .catch((err) => {
        console.log('--StudyPlan--switchCircleStudyPlanStatus--err--:', err);
      });
  };

  //状态更改--固定计划接口
  const switchFixedStudyPlanOpenStatusApi = (guid: string, originOpenStatus: number) => {
    switchFixedStudyPlanStatus({ guid, openStatus: originOpenStatus ? 0 : 1, entId })
      .then((res: any) => {
        _noPermissionToSwitch(res);
      })
      .catch((err) => {
        console.log('--StudyPlan--switchFixedStudyPlanStatus--err--:', err);
      });
  };
  // 状态更改--线下培训接口
  const switchOfflinePlanApi = (guid: string, originOpenStatus: number) => {
    const params = {
      planCourseId: guid,
      openStatus: originOpenStatus ? 0 : 1,
    };
    updateOfflinePlanStatus(params).then((res: any) => {
      const { code } = res;
      if (code === '200') {
        message.success('状态修改成功');
        refreshTable();
      }
    });
  };
  /**
   * @description 修改状态
   * @param record
   * @returns
   * 字段说明：status 100待发布 200已发布 300已结束 400已过期
   * openStatus：1处于开启状态，0处于关闭状态
   * type: '200' 循环计划， '100' 固定计划
   */
  const switchStatus = (record: TableRecord) => {
    if (record.isNewInterface) return message.warning('请前往app操作');
    const { type, openStatus, planCourseId, effectiveTime, cycleTime, status, startTime, studyMethod } = record;
    if (type === '200') {
      //循环学习计划
      if (openStatus === 1) {
        //处于开启状态
        confirm({
          title: '关闭学习计划',
          content: '关闭后本周期任务依然生效，下周期将停止该学习计划，是否确认关闭？',
          centered: true,
          onOk: () => {
            switchCircleStudyPlanOpenStatusApi(planCourseId, openStatus);
          },
        });
      } else {
        // 处于关闭状态
        // 如果当前时间大于生效时间。则弹窗时间弹窗,选时间，确定后，修改时间，再调状态接口，开启
        if (dayjs().isAfter(dayjs(effectiveTime))) {
          setNowModal(1);
          setIsModalShow({ show: true });
          setConfigModal({
            title: '开启学习计划',
            children: (
              <StudyPlanTimeForm
                ref={studyPlanTimeFormRef}
                planCourseId={planCourseId}
                cycleTime={cycleTime!}
                openStatus={openStatus}
              />
            ),
          });
        } else {
          // 每一日一学提醒用户会关闭其他的
          if (cycleTime === 1) {
            confirm({
              title: '开启学习计划',
              content: '每次只可开启一个每一日一学计划，若有其他每一日一学计划则默认更改为关闭状态',
              centered: true,
              onOk: () => {
                switchCircleStudyPlanOpenStatusApi(planCourseId, openStatus);
              },
            });
          } else {
            switchCircleStudyPlanOpenStatusApi(planCourseId, openStatus);
          }
        }
      }
    } else {
      // 如果线下培训时候
      if (studyMethod == 200) {
        //处于开启状态
        confirm({
          title: `${openStatus === 1 ? '关闭' : '开启'}学习计划`,
          content: `确认${openStatus === 1 ? '关闭' : '开启'}该学习计划吗？`,
          centered: true,
          onOk: () => {
            switchOfflinePlanApi(planCourseId, openStatus);
          },
        });
      } else {
        //固定学习计划
        if (openStatus === 1) {
          //处于开启状态
          confirm({
            title: '关闭学习计划',
            content: '确认关闭该学习计划吗？',
            centered: true,
            onOk: () => {
              switchFixedStudyPlanOpenStatusApi(planCourseId, openStatus);
            },
          });
        } else {
          // 处于关闭状态
          // 如果是已过期，已结束。直接提示不能开启
          if (status === 300 || status === 400) {
            message.warning(`该计划已${status === 300 ? '已结束' : '已过期'}，不可重新开启`);
          } else {
            if (dayjs().isAfter(dayjs(startTime))) {
              message.warning('超出计划开始时间，不可开启');
            } else {
              switchFixedStudyPlanOpenStatusApi(planCourseId, openStatus);
            }
          }
        }
      }
    }
  };

  //删除学习计划
  const deleteStudyPlan = (planCourseId: string, type: string, delMethod: any) => {
    confirm({
      title: '删除学习计划',
      content: '确认删除该学习计划吗？',
      centered: true,
      onOk: () => {
        let request: any;
        if (delMethod == 200) {
          request = delOfflineStudyPlan(planCourseId);
        } else {
          if (type === '200') {
            request = deleteCircleStudyPlan({ guid: planCourseId });
          } else {
            request = deleteFixedStudyPlan({ ids: planCourseId });
          }
        }

        request
          .then((res: any) => {
            if (res.code === '200') {
              message.success('删除成功');
              refreshTable();
            }
          })
          .catch((err: any) => {
            console.log('--StudyPlay--deleteStudyPlan--err--:', err);
          });
      },
    });
  };
  const exportCode = (record: any) => {
    setNowModal(2);
    setIsModalShow({ show: true });
    setConfigModal({
      title: '导出二维码',
      children: (
        <ExportCodeModal
          ref={exportCodeModalRef}
          planCourseId={record.planCourseId}
          planTypeName={
            record.studyMethod == 200 ? '线下培训' : record.type === '200' ? `每${record.cycleTime}日一学` : '固定时间'
          }
          // cycleTime={cycleTime!}
          // openStatus={openStatus}
        />
      ),
    });
  };
  const columns: YmColumnsType<TableRecord> = useMemo(
    () => [
      {
        title: '计划名称',
        dataIndex: 'name',
        key: 'name',
        ellipsis: true,
        width: 220,
      },
      {
        title: '学习对象',
        dataIndex: 'studyObject',
        key: 'studyObject',
        width: 220,
        ellipsis: true,
        render: (text, record) => (
          <span>
            {text
              ? text
                  .split(',')
                  .map((v: string) => StudyObjectEnum[Number(v)])
                  .join(',')
              : ''}
          </span>
        ),
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100,
        ellipsis: true,
        render: (text, record) => (
          <span>
            {record.studyMethod == 200 ? '线下培训' : text === '200' ? `每${record.cycleTime}日一学` : '固定时间'}
          </span>
        ),
      },
      {
        title: '修改时间',
        dataIndex: 'modifyTime',
        key: 'modifyTime',
        width: 120,
      },
      {
        title: '状态',
        dataIndex: 'openStatus',
        key: 'openStatus',
        width: 80,
        render(value, record) {
          return (
            <Switch
              checked={value}
              onChange={() => {
                switchStatus(record);
              }}
            ></Switch>
          );
        },
      },
      {
        title: '操作',
        key: '_operate',
        width: 220,
        fixed: 'right',
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  setCurPlanCourseId(record.planCourseId);
                  setCurrPlanType(record.type);
                  setCurrStudyMethod(record.studyMethod);
                  setDrawerOpen(true);
                }}
              >
                <span className="safe-edu_table_operation_text">详情</span>
              </Button>
              <Button
                type="text"
                size="small"
                disabled={!record.showEditButton}
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  if (record.isNewInterface) return message.warning('请前往app操作');
                  navigator(
                    `/plannedManage/addStudyPlan?type=edit&planType=${record.type}&planCourseId=${record.planCourseId}&studyMethod=${record.studyMethod}`,
                  );
                }}
              >
                <span className="safe-edu_table_operation_text">编辑</span>
              </Button>
              <Button
                type="text"
                size="small"
                disabled={!!record.openStatus}
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  deleteStudyPlan(record.planCourseId, record.type, record.studyMethod);
                }}
              >
                <span className="safe-edu_table_operation_text">删除</span>
              </Button>
              {record.studyMethod == 200 ? (
                <Button
                  type="text"
                  size="small"
                  onClick={(e: React.MouseEvent) => {
                    e.stopPropagation();
                    exportCode(record);
                  }}
                >
                  <span className="safe-edu_table_operation_text">导出二维码</span>
                </Button>
              ) : null}
            </Space>
          );
        },
      },
    ],
    [refreshFlag, curPlanCourseId],
  );

  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };

  //点击modal保存按钮
  const confirmModal = () => {
    if (studyPlanTimeFormRef.current) {
      studyPlanTimeFormRef.current
        .onSubmit()
        .then((values) => {
          const { planCourseId: guid, effectiveTime, openStatus: originOpenStatus } = values;
          Promise.all([
            updateCircleStudyPlanEffectiveTime({ guid, effectiveTime }),
            switchCircleStudyPlanStatus({ guid, openStatus: originOpenStatus ? 0 : 1, entId }),
          ])
            .then((res) => {
              if (res[0].code === '200' && res[1].code === '200') {
                message.warning('状态修改成功');
                refreshTable();
              }
            })
            .catch((err) => {
              console.log('--StudyPlan--updateCircleStudyPlanEffectiveTime/switchCircleStudyPlanStatus--err--:', err);
            });
        })
        .finally(() => {
          closeModal();
        });
    } else if (exportCodeModalRef.current) {
      exportCodeModalRef.current.onSubmit().then((values) => {
        const { codePros, planCourseId, selectArr, startTime, endTime } = values;

        const params = {
          wSize: sourceData[selectArr[0]].width,
          hSize: sourceData[selectArr[0]].height,
          msg: '',
        };
        const msgBefore = 'yunMai56/qrCode/Learning/card?planId=' + planCourseId + '&startDate=';
        if (codePros.codeTimeType == 1) params.msg = msgBefore + '2000-01-05 00:00:00&endDate=2999-12-31 23:59:59';
        else if (codePros.codeTimeType == 2) params.msg = msgBefore + startTime + '&endDate=' + endTime;

        getOffLineCodeUrl(params).then((res: any) => {
          const { code, data } = res;
          if (code === '200') {
            window.open(data.url, '_target');
          }
        });
      });
    }
  };

  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: nowModal == 2 ? 720 : 420,
    centered: true,
    destroyOnClose: true,
    footer:
      nowModal == 2
        ? []
        : [
            <Button key="back" onClick={closeModal}>
              取消
            </Button>,
            <Button type="primary" key="save" onClick={confirmModal}>
              保存
            </Button>,
          ],
    onCancel: closeModal,
  };

  //课件详情drawer 配置
  // 该详情也要区分 是boss 还是 企业/协会
  const drawerConfig = useMemo(
    () => ({
      title: '计划详情',
      width: DRAWERWIDTH,
      open: drawerOpen,
      onClose: () => {
        setDrawerOpen(false);
      },

      destroyOnClose: true,
      children:
        currStudyMethod == 200 && curPlanCourseId && currPlanType ? (
          <StudyOfflineDetail planCourseId={curPlanCourseId} />
        ) : curPlanCourseId && currPlanType ? (
          <StudyPlanDetail planCourseId={curPlanCourseId} planType={currPlanType} />
        ) : null,
    }),
    [curPlanCourseId, drawerOpen, currPlanType, currStudyMethod],
  );

  const { handleColumns, onColumnsChange, loading } = useCacheColumns({
    checkType: 23,
    columns: columns!,
  });

  return (
    <div className="safe_edu_page ">
      <CusModal {...modalConst} {...configModal} />
      <CusDrawer {...drawerConfig} />
      <StudyPlanTemplateDrawer ref={studyPlanTemplateDrawerRef} entId={entId} />
      {loading ? (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}
        >
          <Spin spinning={loading}></Spin>
        </div>
      ) : (
        <YmTable<TableRecord, SearchValue>
          rowKey="planCourseId"
          columns={handleColumns}
          toolBar={{
            onColumnsChange,
            prefixNode: (
              <>
                <Button
                  type="primary"
                  onClick={() => {
                    navigator('/plannedManage/addStudyPlan?type=add');
                  }}
                >
                  新增
                </Button>
                <Button
                  type="primary"
                  onClick={() => {
                    studyPlanTemplateDrawerRef.current?.open();
                  }}
                >
                  选择计划模版
                </Button>
              </>
            ),
          }}
          searchForm={{
            defaultCollapsed: true,
            span: 6,
            labelCol: { style: { width: 108 } },
            formItems: [
              {
                name: 'name',
                label: '名称',
                valueType: {
                  inputProps: {
                    autoComplete: 'off',
                  },
                },
              },
              {
                name: 'studyObject',
                label: '学习对象',
                valueType: {
                  type: 'select',
                  selectProps: {
                    mode: 'multiple',
                    placeholder: '请选择',
                    options: ENTSTUDYOBJECTOPTIONS,
                    showSearch: false,
                    maxTagCount: 1,
                  },
                },
              },
            ],
          }}
          request={async ({ page }, value = {}) => {
            const result = await secPlanList({ ...value, entId }, page?.pageIndex, page?.pageSize);
            return {
              list: result.list.map((listItem: TableRecord) => {
                const { type, openStatus, startTime, status } = listItem;
                let showEditButton = true;
                if (type === '100') {
                  //固定时间
                  if (openStatus === 1) {
                    //开启的话，不能编辑
                    showEditButton = false;
                  } else {
                    // 关闭状态下
                    if (dayjs().isAfter(startTime)) {
                      //当前时间大于已开始时间，则不可编辑
                      showEditButton = false;
                    }
                  }
                }
                // 循环计划，任何状态都能编辑
                if (status === 300 || status === 400) showEditButton = false;
                return {
                  ...listItem,
                  showEditButton,
                };
              }),
              total: result.total,
            };
          }}
          requestOptions={{
            reFreshDep: [refreshFlag],
          }}
        />
      )}
    </div>
  );
}
